<?php
/**
    This collection of functions (libary) is licensed under GPL2.
    See LICENSE or www.gnu.org for more details.

    @author Henri Ranki 10.11.2000

    dzScriptSeppo class is defined here. It is used to produce
    scrits on html forms.

    dzScriptSeppo reads the inifiles that is needed to produce script
    code (dzwidget.ini and dzfeatures.ini).

    While iterating through Dataxi source found widgets are told to
    dzScriptSeppo. Then it is asked to return the script code that is
    placed in the beginning of every produced html source. (head script)
    Later on dzScriptSeppo gives the script that is inserted into widget
    entity definition.

    Big changes 15.3.2001. A part of dzScriptSeppo was separated to a
    different class named dzScriptInfo. DzScriptInfo contains all the
    view specific data.

    $Id: dzseppo.php 595 2006-04-03 16:00:47Z jyry $
*/

include_once("sodebug.php");
include_once("sosqlhi.php");
include_once("sostring.php");
include_once("soset.php");
include_once("sofiles.php");
include_once("sogeneric.php");

include_once("dzdatetime.inc");
include_once("dzwidget.php");
include_once("dzfeatures.php");
include_once("dzgeneric.php");
include_once("dzfeaturespool.php");
include_once("dztemplate.php");
include_once("dzpurkki.php");
include_once("dzahjo.php");
include_once("dzkeycodes.php");

class dzScriptSeppo extends soBaseClass{
    var $__WidgetBase;       /* dzWidgetSet object */
    var $__FeatureBase;      /* dzFeatureSet object */
    var $__Template;         /* dzTemplate Pointer to dzTemplate used to get
                                the structure and the properties of the form.
                              */
    var $__Laituri;          /* dzPurkki Pointer to the dzPurkki class that
                                contains the data for the form. */
    var $ScriptFeatureSpool; /* dzScriptFeatureSpool Collects the features
                                needed on the form before head script is made
                              */
    var $__Ahjos;            /* array/dzAhjo List of ahjos */

    /** Constructor
     */
    function dzScriptSeppo(&$TemplatePtr, &$LaituriPtr) {
        /* Save the pointers to dzTemplate and dzPurkki. These are the data
           stores where  all the form data is stored */
        $this->__Template = &$TemplatePtr;
        $this->__Laituri = &$LaituriPtr;

        /* Set the script feature spool point to template. There are already
           some earlier information stored. */
        $this->ScriptFeatureSpool = &$this->__Template->ScriptFeatureSpool;

        $this->__WidgetBase = new dzWidgetSet();
        $this->__FeatureBase = new dzFeatureSet();
        $this->Error =
            $this->__FeatureBase->Error || $this->__WidgetBase->Error;

        global $_DZ_GLOBALS;
        $this->__Ahjos = unserialize($_DZ_GLOBALS[DZGV_AHJOLIST]);
        if ($this->__Ahjos) {
            for ($i = count($this->__Ahjos) -1; $i >= 0; $i--) {
            $this->__Ahjos[$i]->setTemplate($TemplatePtr);
        };
        } else {
            $this->__Ahjos = getAhjoList($this->__Template);
        };
        $_DZ_GLOBALS[DZGV_AHJOLIST] = serialize($this->__Ahjos);
    } // dzScriptSeppo()


    /** Find out the special features needed by this column.
     *  @param dzSourceEntity $EntityThe entity which precode is produced
     *  @return soSet Features needed for this single field
     */
    function parseFeatures($Entity) {
        $result = new soSet();
        $mode = $this->__Template->getViewData(DZ_VI_MODE);

        $default = $this->__Template->getColProperty(
            $Entity->Name, DZCPT_CONTROL, DZCP_DEFAULT);

#        if ((($mode == DZM_NEW) || ($mode == DZM_EDIT)) &&
#            ($default == DZDCV_AUTO)) {
#            $needed_features = soExplode("deny_focus", " ");
#            $result->joinArrayAsKeys($needed_features);
#        } // if $readonly

        return $result;
    } // parseFeatures


    /** Get the code for listbox
     *  Create table with given amount of columns
     *  @param string $Name Column name
     *  @param soSet/string $Items The listbox item names and values
     *  @param string $Value The value of the column
     *  @param DZM_* Mode (browse, edit etc.)
     *  @return The code for the list box
     */
    function getDropdownBox($Name, $Items, $Value, $Mode, $Required, $Readonly) {
        $code = "<SELECT NAME='$Name' SIZE=1";
        if (($Mode == DZM_BROWSE) || 
           (in_array($Mode, array(DZM_EDIT, DZM_NEW)) && $Readonly)) {
           	$code .= ' disabled class=readonly';
           };
		$code .= ">\n";
        if (($Mode == DZM_QUERY) || !$Required) $code .= "<OPTION VALUE=''>\n";

        $db_vals = $Items->getKeys();
        $icount = count($db_vals);
        $item_index = 0;
        for ($c = 0; $c < $icount; $c++) {
            $selected = ($db_vals[$c] == $Value) ? " SELECTED" : "";
            $title = $Items->getItem($db_vals[$c]);
            $title = soSwapStr($title, "_", " ");
            if (($Mode != DZM_BROWSE) ||
                (($Value == $db_vals[$c]) &&
                 (gettype($Value) == gettype($db_vals[$c])))) {
                $row = "<OPTION VALUE='".$db_vals[$c]."' $selected>$title\n";
                $code .= $row;
            };
        } // for
        $code .= "</SELECT>\n";

        return $code;
    } // getDropdownBox


    /** Get the code for radio group
     *  Create table with given amount of columns
     *  @param soSet/str $Items The radio button item names and values
     *  @param str $Name Column name
     *  @param int $Cols The amount of columns in the created table.
     *                   If zero fit all on the row
     *  @param str $Align Whether "right" or "left". Justifies the component
     *                    place according to the titile.
     *  @param str $Checked The value that is checked by default
     *  @return The code for the radio group
     */
    function getRadioGroup($Name, $Items, $Cols, $Align, $Checked, $Mode) {
        $result = "<TABLE>\n";
        $db_vals = $Items->getKeys();
        $icount = count($db_vals);
        $item_index = 0;
        /* If column count not given */
        if ($Cols == 0) $Cols = $icount;

        /* Loop while all the items have been inserted. */
        while ($item_index < $icount) {
            $result .= "<TR>";
            /* Create one row*/
            for ($c = 0; $c < $Cols; $c++) {
                $title = $Items->getItem($db_vals[$item_index]);
                $title = soSwapStr($title, "_", " ");
                if ($db_vals[$item_index] == $Checked) {
                    $checked_txt = " CHECKED ";
                } else {
                    $checked_txt = "";
                }; // else if
                $component = "<INPUT TYPE='radio' NAME='".$Name."' value='".
                            $db_vals[$item_index]."'".$checked_txt;
                if ($Mode == DZM_BROWSE) $component .= ' disabled class=readonly';
                          
				$component .= ">";

                $Align = soCaseConv($Align, "L");
                if ($Align == "right") {
                    $field = $title.$component;
                } else {
                    $field = $component.$title;
                } // if

                $result .= "<TD>".$field."</TD>\n";
                $item_index++;
                /* If this was the last item break the for loop */
                if ($item_index >= $icount) break;
            } // for
            $result .= "</TR>\n";
        } // while
        $result .= "</TABLE>\n";

        return $result;
    } // getRadioGroup


    /** Returns widget script.
     *  Returns the code that is placed inside of the widget entity definition
     *  in the html code. Sets the name, value and user defined html options
     *  for the widget. User defined html options overrides the default html
     *  options defined in features.ini.
     *
     *  @param object dzSourceEntity $Entity The entity which precode is
     *  produced
     *  @param string $FieldName The name of the field on the form
     *  @param any $Value The value of the field
     *  @param string $Align How the value is aligned in the field
     *  @return string Code for the field
     */
    function getWidgetScript(&$Entity, $FieldName, $Value, $Required,
                             $Align="") {
        /* Get the features that is needed by this field. */
        $field_features = $this->parseFeatures($Entity);

        /* Get the name of the column. It is the entity name where the period
           is replaced with special character DZ_DR_STR.
           Replacement is done due to restrictions in used script language in
           browser.*/
        $tag_name = soSwapStr($Entity->Name, ".", DZ_DR_STR);

        /* Loop through ahjos and try to add this field */
        $acount = count($this->__Ahjos);
        for ($c = 0; $c < $acount; $c++) {
            $ahjo = &$this->__Ahjos[$c];
            $ahjo->addField($Entity, $tag_name, $FieldName, $Value);
            $field_features->joinArrayAsKeys($ahjo->getScriptFeatures());
        } // for

        $widget_type = $this->__Template->getColProperty(
            $Entity->Name, DZCPT_CONTROL, DZCP_WIDGET);

        if (!$widget_type) {
            /* No widget type defined get the default widget. First get the
               data type */
            $data_type = $this->__Template->getColProperty(
                $Entity->Name, DZCPT_STRUCT, DZCP_TYPE);
            $widget_type = dzGetIniItem("widgets", $data_type, "dataxi");
            if (!$widget_type) {
                /* If data type was unknown just use text box */
                soDebug("dzSeppo->getWidgetScript: ".
                        "No widget for datatype '$data_type' ".
                        "Using textbox.", SOD_LO);
                $widget_type = dzGetIniItem("widgets", "text", "dataxi");
            } // if $widget_name

        } // if $widget_type

        /* If widget of this type exists add this widget to the set of the used
           widgets */
        if ($this->__WidgetBase->widgetExist($widget_type)) {
            $this->__Template->ScriptFeatureSpool->addToUsedWidgets(
                $widget_type);
            soDebug("dzScriptSeppo->getWidgetScript: Added ".
                    $widget_type." widget", SOD_DET);
        } else {
            soDebug("dzScriptSeppo->getWidgetScript: Couldn't find widget ".
                    $widget_type, SOD_LO_E);
            return ""; // <-- EXIT
        }; // else if

        /* Get the information on the widget */
        $widget = $this->__WidgetBase->Widgets->getItem($widget_type);
        $script = "<NOBR>";

        $closed = 0;
        $mode = $this->__Template->getViewData(DZ_VI_MODE);
        switch (strtoupper($widget->Type)) {
            case DZW_TEXTAREA:
                $script .= "<textarea ";
                break;
            case DZW_CHECKBOX:
                /* Let's start producing the script */
                $script .= "<input value=1";
                /* Add set the html widget type */
                $script = soJoinStr($script, " ", "type=checkbox", 1);
                /* A checkbox has a special way to set its state. */
                if ($Value) $script = soJoinStr($script, " ", "checked=1", 1);
                break;

            case DZW_RADIOBOX:
                $btn_align = $this->__Template->getColProperty(
                    $Entity->Name, DZCPT_CONTROL, DZCP_RB_ALIGN);
                $num_cols = $this->__Template->getColProperty(
                    $Entity->Name, DZCPT_CONTROL, DZCP_RB_COLS);
                $iface_name = $this->__Template->getColProperty(
                    $Entity->Name, DZCPT_CONTROL, DZCP_IFACE);
                $items = $this->__Template->getInterface($iface_name);
                if ($num_cols == "") $num_cols = $items->size();
                $rb_code = $this->getRadioGroup($FieldName, $items, $num_cols,
                                                $btn_align, $Value, $mode);
                $script .= soJoinStr($script, "\n", $rb_code, 1);
                $script .= "</NOBR>\n";
                $closed = 1;
                break;

            case DZW_DROPDOWNBOX:
                $iface_name = $this->__Template->getColProperty(
                    $Entity->Name, DZCPT_CONTROL, DZCP_IFACE);
                $req = $this->__Template->getColProperty(
                    $Entity->Name, DZCPT_STRUCT, DZCP_REQUIRED);
                $items = $this->__Template->getInterface($iface_name);
                $dd_code .= $this->getDropdownBox($FieldName, $items,
                                                  $Value, $mode, $req, 0);
                $script .= soJoinStr($script, "\n", $dd_code, 1);
                $script .= "</NOBR>\n";
                $closed = 1;
                break;

            case DZW_DATEBOX:
                $this->__Template->addInitAction(DZIA_INIT_DATE_BOX);
                $script .= "<table border=0 cellspacing=0 cellpadding=0>".
                    "<tr><td><input type='text' value='".$Value."'";
                if ($Align != "") {
                    if ($Align == "right") {
                        $Align="rtl";
                    } else {
                        $Align="ltr";
                    }; // else if
                    $script = soJoinStr($script, " ", "dir=$Align", 1);
                } // if
                break;

            default:
                /* Let's start producing the script */
                $script .= "<input";
                /* Add set the html widget type */
                $script = soJoinStr($script, " ", "type=".$widget->Type, 1);
                /* Set the given value */
                $script = soJoinStr($script, " ", "value=\"".$Value."\"", 1);
                if ($Align != "") {
                    if ($Align == "right") {
                        $Align="rtl";
                    } else {
                        $Align="ltr";
                    }; // else if
                    $script = soJoinStr($script, " ", "dir=$Align", 1);
                } // if
        } // switch

        if (!$closed) {
            $format_options = $this->__Template->getColProperty(
                $Entity->Name, DZCPT_FORMAT);
            $script = soJoinStr($script, " ", $format_options, 1);
            if ($Required && ($mode != DZM_BROWSE)) {
                $script = soJoinStr($script, " ", "class=req", 1);
            }; // if

            /* First set the widget name */
            if ($FieldName == "") {
                soDebug("dzScriptSeppo->getWidgetScript: Widget had no name",
                        SOD_HI);
                return "";    // <-- EXIT
            } // if
            $script = soJoinStr($script, " ", "name=".$FieldName, 1);

            /* Add properties to script.  */
            $properties = new soSet();
            $prop_set = $this->__WidgetBase->getRequiredProps($widget_type, $mode);

            /* Add default properties. These does not override the user
               properties. */
            $properties->joinSet($prop_set);
            $prop_arr = $properties->getAsArray();
            while (list ($key, $val) = each ($prop_arr)) {
                $script = soJoinStr($script, " ", "$key=$val", 1);
            } // while

	        /* Add event handlers to script */
	        $eHandlers = new soSet();
	
	        /* Find out the features needed for this widget */
	        $featSet = $this->__WidgetBase->getRequiredFeats($widget_type, $mode);
	
	        /* Insert the features specific for this field */
	        $featSet->joinSet($field_features);
	        $featArr = $featSet->getKeys();
	        $icount = count($featArr);
	        for ($c = 0; $c < $icount; $c++) {
	            $feat = $this->__FeatureBase->Features->getItem($featArr[$c]);
	            $event = $feat->Event;
	            if ($event != "") {
	                 $handlers = $eHandlers->getItem($event);
	                 if (soIsNull($handlers)) $handlers = "";
	                 $handlers = soJoinStr($handlers, "; ",
	                                       $feat->EventHandler, 1);
	                 soDebug("Event=$event Handlers=$handlers", SOD_DET);
	                         $eHandlers->setItem($event, $handlers);
	            }
	        } // for
	
	        /* Now we got the events in soSet and handlers to call assigned
	           them as the value. Next produce a string that is inserted into
	           html code. */
	        $arr = $eHandlers->getAsArray();
	        while (list ($key, $val) = each ($arr)) {
	            $script = soJoinStr($script, " ", "$key=\"$val;\"", 1);
	        }; // while
	
	        if ($mode == DZM_BROWSE) {
	            $script = soJoinStr($script, ' ', 'readonly=1 disabled class=readonly', 1);
	        };
	        /* Some widget has special treatment */
	        switch (soCaseConv($widget->Type, "U")) {
	            case DZW_TEXTAREA:
	                $script .= ">";
	                /* Set the given value */
	                $script .= $Value;
	                $script .= "</textarea>";
	                break;
	
	            case DZW_DATEBOX:
	                $script .= "></td>";
	                if ($mode != DZM_BROWSE) {
	                    $site_inc = dzGetIniPath(DZID_SITE_INC_FOLDER);
	                    $date_format = $this->getDateFormatStr();
	                    $script .= "<td>\n".
	                               "<a href='javascript: void(0);' ".
	                               "onmouseover=".
	                               "'if (timeoutId) clearTimeout(timeoutId); ".
	                               "return true;' ".
	                               "onmouseout=".
	                               "'if (timeoutDelay) calendarTimeout();' ".
	                               "onclick=\"g_Calendar.setTitles(".
	                               DZJSO_MONTH.",".DZJSO_DAY.
	                               "); g_Calendar.show(event,'NalleForm.".
	                               $FieldName."',true, '".$date_format."', '".
	                               "', '"."'); return false;\">\n".
	                               "<img src='".$site_inc.
	                               "/calendar.gif' name=imgCalendar".
	                               " width=34 height=21 border=0></a>\n";
	                }; // if
	                $script .= "</td></tr></table>\n";
	                break;
	
	            default:
	                $script .= ">";
	        } // switch
	
	
	        /* If pick is defined, put the pick-btn next to col's component */
	        $pick_define = $this->__Template->getColProperty(
	            $Entity->Name, DZCPT_CONTROL, DZCP_PICK);
	        if (($pick_define != "") && ($mode != DZM_BROWSE)) {
	            global $_DZ_GLOBALS;
	            $key = dzGetIniItem("keymap", "pick", "app");
	            if ($key == "") $key = dzGetIniItem("keymap", "pick", "dataxi");
	            else if ($key == "") $key = "c-l";
	            $pick_key = $_DZ_GLOBALS[DZGV_KEYCODES][$key];
	            /* Create the event handlers for the del-button */
	            $pick_event = "\"submitNalle('nalle', '$FieldName', ".
	                          "'EKeyboard', '$pick_key');\"";
	
	            $script .= "<INPUT TYPE=BUTTON VALUE='...' OnClick=$pick_event>";
	        } // $pick_define
	        $script .= "</NOBR>";
        }; // if !$done

        return $script;
    } // getWidgetScript


    /** Get the settings for the JavaScrip environment
     *
     */
    function getGlobalJSParameters() {
        $result = "";
        /* The browser type and version is set. */
        $browser = soGetBrowser().soGetBrowserVersion();
        $result .= "var ".DZJSO_BROWSER." = '".$browser."';\n";

        /* Set the day that starts week */
        $day = dzGetIniItem(DZIS_GENERAL, DZID_START_WEEK, "app");
        if ($day == "sun") {
            $day = 0;
        } else {
            $day = 1;
        } // if
        $result .= "var ".DZJSO_START_DAY." = ".$day.";\n";

        return $result;
    } // getGlobalJSParameters


    /** Return the label texts that are used in JavaScripts
     *  The user's language is used
     */
    function getTranslations() {
        global $DZ_MONTHS, $DZ_SHORT_DAYS;
        $result = "";

        /* Get all the given labels from the translate file. */
        $trans_file_name =
            dzGetIniItem(DZIS_SYS, DZID_JS_TRANSLATIONS, "dataxi");
        if ($trans_file_name == "")
            $trans_file_name = DZ_DEFAULT_JS_TRANLATIONS_FILE;
        $trans_file_path = dzGetDataxiPath();
        $trans_file = "file://".soPathJoin(array($trans_file_path,
                                                 $trans_file_name));
        $lang = $this->__Template->SessionInfo->Lang;
        $ini = new soIni($trans_file);

        $scount = $ini->getSectionCount($ini);
        for ($c = 0; $c < $scount; $c++) {
            $label = $ini->getValue($c, $lang, 0);

            /* If language is not specified, then use the default */
            if (!$label) $label = $ini->getValue($c, "default", 0);
            $tag_name = $ini->getSectionName($c);

            /* If even no default value is defined use the tag name. */
            if (!$label) $label = $tag_name;
            $result .= "var dzLabel_".$tag_name." = '".$label."';\n";
        } // for

        /* Set the month and day names in user's lanquage */
        $lang = $this->__Template->SessionInfo->Lang;
        if (!in_array($lang, $DZ_MONTHS)) $lang = "default";
        $month_titles = $DZ_MONTHS[$lang];
        if (!in_array($lang, $DZ_SHORT_DAYS)) $lang = "default";
        $day_titles = $DZ_SHORT_DAYS[$lang];

        $month_titles = soArrayAddQuotes($month_titles, "'");
        $day_titles = soArrayAddQuotes($day_titles, "'");

        $result .= "var ".DZJSO_MONTH." = new Array(".
                    implode(",", $month_titles).");\n";
        $result .= "var ".DZJSO_DAY." = new Array(".
                    implode(",", $day_titles).");\n";

        return $result;
    } // getTranslations


    /** Produces the head script for the view according to the widgets and
     *  the features that are needed. Head script includes all the functions
     *  and data structures needed to implement the features on the form sent
     *  to client.
     *  @return string The produced script
     */
    function getHeadScript() {
        global $_DZ_GLOBALS;
        $script = "<script language='JavaScript'><!--\n";

        /* Check if we have any filter fields on the form */
        if (soGetClass($this->__Laituri) == "dzlaituri") {
            $filter_seed_groups = $this->__Laituri->getFilterSeedGroups();
            soDebug("dzScriptSeppo: Filter groups=".implode(",",
                    $filter_seed_groups), SOD_DET);
            $this->__Template->ScriptFeatureSpool->addGenFeatures(
                                        "filter_group general_post_process");
        } // if soGetClass

        $features = new soSet();
        /* 1st, produce custom code for several features. Ahjos are used for
           that. Loop through ahjos and collect the code from each. */
        foreach ($this->__Ahjos as $ahjo) {
            $custom_code = $ahjo->getCode();
            if ($custom_code) $custom_code .= "\n\n\n";
            $script .= $custom_code;
            $features->joinArrayAsKeys($ahjo->getScriptFeatures());
        } // foreach

        /* Parse the features need to be implemented in the heads script */
        $this->parseReqFeatures();

        /* Get the dir for the scripts depending on the clients browser */
        $browser = soGetBrowser().soGetBrowserVersion();
        soDebug("dzScriptSeppo: Client is using $browser", SOD_DET);

        $includes = "";
        $links = !dzNoLinking();
        if ($links) {
            $script_path = dzGetIniPath(DZID_SITE_INC_FOLDER);
        } else {
            $script_path = dzGetIniPath(DZID_SITE_INC_FOLDER, 1);
            $includes .= "<script language='JavaScript'>";
        }; // else if

        $features->joinArrayAsKeys(
            $this->ScriptFeatureSpool->getReqFeatures());
        $featsArray = $features->getKeys();

        $script .= $this->getInitCode();
        foreach ($featsArray as $arr_key) {
            $feature = $this->__FeatureBase->Features->getItem($arr_key);
            $scriptStream = soJoinStr($scriptPath, "/", $feature->Stream, 1);

            if ($feature->Constants) {
                $reqConsts = $feature->Constants->getAsArray();
            } else {
                $reqConsts = array();
            }; // else if
            if (count($reqConsts)) $script .= "\n// Constants\n";
            while (list($key, $val) = each ($reqConsts)) {
                $script .= $key." = ".$val.";\n";
            }; // while

            /* Include the required JavaScripts features. */
            if ($feature->Elements) {
                $req_elem_str = $feature->Elements->getItem($browser);
                if ($req_elem_str == "")
                    $req_elem_str = $feature->Elements->getItem("default");
                $incl_js_files = soExplode($req_elem_str, " ");
            } else {
                $incl_js_files = array();
            };

            /* Produce the include codes */
            foreach($incl_js_files as $file) {
                $path = soPathJoin(array($script_path, $file));
                if ($links) {
                    $includes .= "<script language='JavaScript' src='".$path.
                                 "' type='text/javascript'></script>\n";
                } else {
                    $tmp = $_DZ_GLOBALS[DZGV_INI_SCRIPTS][$path];
                    if (!$tmp) {
                        soDebug("dzSeppo->getHeadScript: read and caching ".
                                "script '".$path."'", SOD_DET);
                        $tmp = soFileToString($path);
                        $_DZ_GLOBALS[DZGV_INI_SCRIPTS][$path] = $tmp;
                    }; // if
                    $includes .= $tmp;
                };
            } // foreach
        }; // for $c
        if (!$links) $includes .= "</script>\n";
        $script .= "\n//--></script>\n".$includes;
        /* Set global JavaScript parameters and label translations */
        $script .= "<script language=\"JavaScript\"><!--\n".
                   $this->getGlobalJSParameters().
                   $this->getTranslations().
                   "\n//--></script>";

        return $script;
    } // getHeadScript


    /** Create the piece of code that initializes the form
     */
    function getInitCode() {
        $script .= "function initCode() {\n";
        $init_set = $this->ScriptFeatureSpool->getAttrib(DZSA_INIT_ACTION);
        if (soGetClass($init_set) == "soset") {
            $init_arr = $init_set->getAsArray();
            foreach ($init_arr as $action => $parameters) {
                $parameter = $parameters[0];
                soDelElement($parameters, 0);
                /* Check that the widget given as a parameter exists.
                   If not try to change the leading e to n in the widget
                   name. Maybe the row has changet it status. */
                $base_name = soSubStr($parameter, 1,
                                      strlen($parameter) - 1);
                if ($this->__Template->ClientWidgetMap->itemExists("e".
                                                            $base_name) ) {
                    $base_name = "e".$base_name;
                } else if ($this->__Template->ClientWidgetMap->itemExists("n".
                                                               $base_name) ) {
                    $base_name = "n".$base_name;
                } else {
                    $base_name = "s".$base_name;
                } // if


                /* Setting the document location does not work with all the.
                   browsers Set the location only when it works. */
                $browser = soGetBrowser().soGetBrowserVersion();
                if ($browser != "mozilla5")
                    $set_location_str = "location='#L".$base_name."';\n";
                else
                    $set_location_str = "";


                switch ($action) {
                    case DZIA_SET_FOCUS:
                        /* scroll the screen. Works only with some browsers */
                        $script .= $set_location_str;
                        $script .= "setTimeout('document.NalleForm.".
                                   $base_name.".focus()', 500);\n";
                        break;

                    case DZIA_SET_LAST_FILTER:
                        $script .= "LastFilterPos='".$base_name."';\n";
                        break;

                    case DZIA_SET_ERROR_FLAG:
                        $script .= "ErrorField='".$base_name."';\n";
                        break;

                    case DZIA_TO_NEXT_COMPONENT:
                        /* scroll the screen. Works only with some browsers */
                        $script .= $set_location_str;
                        $script .= "col=extractCol('$base_name');\n";
                        $script .= "row = extractRow('$base_name');\n";
                        $script .= "grp = extractGrp('$base_name');\n";
                        $script .= "var newComponent = ".
                                   "getNextComponent(row,col,0,grp);\n";
                        $cmd = "document.NalleForm.'+newComponent+'.focus()";
                        $script .= "setTimeout('$cmd', 500);\n";
                        break;

                    case DZIA_OPEN_NEW_WINDOW:
                        $params = implode(",", $parameters);
                        $window_name = "dzWindow".time();
                        $script .= "NewWnd = window.open('$parameter', ".
                                   "'$window_name', ',$params');\n";
                        break;

                    case DZIA_UPDATE_CALC_FIELDS:
                        $script .= "loopCalcFields();\n";
                        break;

                    case DZIA_SUSPEND_TIMER:
                        $timeout_msecs = $parameter * 60000;
                        $command = "submitNalle('stonga', 'ESuspend', ".
                                   "'ESuspend', '');";
                        $script .= "setTimeout(\"$command\", ".
                                   $timeout_msecs.");\n";
                        break;

                    case DZIA_INIT_DATE_BOX:
                        $script .= "new Calendar(new Date());\n".
                                   "if (browser.ns4){\n".
                                   "if (typeof document.NSfix == ".
                                   "'undefined'){\n".
                                   "document.NSfix = new Object();".
                                   "document.NSfix.".
                                   "initWidth=window.innerWidth;".
                                   "document.NSfix.".
                                   "initHeight=window.innerHeight;\n".
                                   "}}\n";
                        break;
                } // switch $action
            } // foreach
        } // if soGetClass($init_set)
        $script .= "}\n";

        return $script;
    } // getInitCode


    /** Parse the set of features needed to implement the current
     *  form in the current mode.
     */
    function parseReqFeatures() {
        /* Atleast the following features are needed */
        $def_features = dzGetIniItem("sys", "features", "dataxi");
        soDebug("dzScriptSeppo: Adding default features: $def_features",
                SOD_DET);
        $this->ScriptFeatureSpool->addGenFeatures($def_features);

        /* Add general features to the required features. These are the
           features that is not related with widgets. */
        $general_features =
            $this->ScriptFeatureSpool->getAttrib(DZSA_GEN_FEATURES);
        $this->ScriptFeatureSpool->addToReqFeatures($general_features);

        $widgets = $this->ScriptFeatureSpool->getUsedWidgets();
        $mode = $this->__Template->getViewData(DZ_VI_MODE);
        $icount=count($widgets);
        foreach ($widgets as $key) {
            $s = $this->__WidgetBase->getRequiredFeats($key, $mode);
            $this->ScriptFeatureSpool->addToReqFeatures($s);
        }; //for
   } // parseReqFeatures


    /** Returns date format string suitable for calendar component.
     */
    function getDateFormatStr() {
        $format = dzGetIniItem(DZIS_GENERAL, DZID_DATE, "app");
        $style = substr($format, 0, 1);
        $delim = substr($format, 1, 1);
        $year_digits = intval(substr($format, 2, 1));
        $pad = (strlen($format) == 3);
        if (!$pad) $pad = 2;

        $year = str_repeat("y", $year_digits);
        $month = str_repeat("m", $pad);
        $day = str_repeat("d", $pad);

        switch ($style) {
            case "j":
                $result = $year.$delim.$month.$delim.$day;
                break;
            case "u":
                $result = $month.$delim.$day.$delim.$year;
                break;
            default: // European
                $result = $day.$delim.$month.$delim.$year;
                break;
        }; // switch

        return $result;
    } // getDateFormatStr

}; // class dzScriptSeppo

?>
